import { ComponentRefSchema } from '../schema/schema';
import { FarrisDesignBaseNestedComponent } from '@farris/designer-element';
import { ComponentSchema } from '@farris/designer-element';
import { omit } from 'lodash-es';
import { DomService, DesignViewModelService } from '@farris/designer-services';

export default class FdComponentRefComponent extends FarrisDesignBaseNestedComponent {

    component;

    /**  实际的组件JSON Schema */
    componentSchemaNode: ComponentSchema;

    /** 实际的组件实例 */
    childComponentInstance = [];

    constructor(component: any, options: any) {
        super(component, options);
    }


    getDefaultSchema(): any {
        return ComponentRefSchema;
    }
    /**
     * 只返回引用节点相关属性
     */
    getSchema(): any {
        const completeSchema: any = super.getSchema();
        return omit(completeSchema, 'contents');
    }


    getTemplateName(): string {
        return 'Component';
    }



    init(): void {
        this.components = [];
        if (this.options.childComponents && this.options.childComponents.length) {
            this.componentSchemaNode = this.options.childComponents.find(c => c.id === this.component.component);
            if (this.componentSchemaNode) {
                const instance: any = this.createComponent(
                    this.componentSchemaNode,
                    this.options,
                    this.componentSchemaNode.id,
                    this.componentSchemaNode.viewModel);

                this.childComponentInstance.push(instance);
            }
        }
    }
    render(): any {
        // 只渲染实际的组件节点，不渲染组件引用节点
        if (this.childComponentInstance.length) {
            return this.renderComponents(this.childComponentInstance);
        }

    }



    attach(element: any): any {

        const superAttach: any = super.attach(element);

        // 只渲染实际的组件节点，不渲染组件引用节点
        if (this.childComponentInstance.length) {
            this.childComponentInstance[0].attach(this.element);
        }

        return superAttach;
    }


    /**
     * 删除组件的回调方法：用于移除配套的Component和ViewModel
     */
    onRemoveComponent() {
        super.onRemoveComponent();
        const serviceHost = this.options.designerHost;
        const dgViewModelService = serviceHost.getService('DesignViewModelService') as DesignViewModelService;
        const domService = serviceHost.getService('DomService') as DomService;

        if (this.childComponentInstance.length) {
            dgViewModelService.deleteViewModelById(this.childComponentInstance[0].component.viewModel);
        }

        domService.deleteComponent(this.component.component);
    }

    getControlShowName() {
        return '';
    }
}
